import { Injectable } from '@nestjs/common'
import { Repository, getConnection } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { UserAddressEntity, UserEntity } from 'src/entities/user.entity'
import to from 'await-to-js'
import { addressListDto, editAddressDto } from './dto/user-address.dto'
@Injectable()
export class AddressService {
  constructor(
    @InjectRepository(UserAddressEntity)
    private readonly userAddressEntityRepository: Repository<UserAddressEntity>,
  ) {}

  async editAddress(body: editAddressDto, user: UserEntity) {
    const [err, result] = await to(
      this.userAddressEntityRepository.save({ ...body, user }),
    )
    if (err) err
    return result
  }

  async getAddress(user: UserEntity) {
    const [err, result] = await to(
      getConnection().manager.query(`SELECT  a.*,
      p1.name country_name, 
      p2.name city_name,  
      p3.name province_name 
      FROM user_address a  
      INNER JOIN province p1 ON a.country_code=p1.code  
      INNER JOIN province p2 ON a.city_code=p2.code 
      INNER JOIN province p3 ON a.province_code=p3.code 
      where a.userId = ${user.id}`),
    )
    if (err) err
    return result
  }

  async setDefaultAddress(id: number, user: UserEntity) {
    let tar = await this.userAddressEntityRepository.findOne(id)
    const isDefault = tar.isDefault
    await getConnection()
      .createQueryBuilder()
      .update(UserAddressEntity)
      .set({ isDefault: false })
      .where({
        user,
      })
      .execute()
    if (!isDefault) {
      await this.userAddressEntityRepository.save({
        ...tar,
        isDefault: true,
      })
    }
    return this.getAddress(user)
  }
}
